import { getWorkshops, getDict } from 'src/boot/common/dict'
import { getTeams } from 'src/boot/factory/factory-calendar'
import { getCustomerSet } from 'src/boot/system/customer-set'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import CommonConfig from 'src/assets/js/config'
import { getCompnies, login } from '../boot/login/login'
import { saveRefreshToken, saveToken, loadToken, loadRefreshToken } from 'yz-help'
import { getMarkSetting } from 'src/boot/program-v2/sign'
import _ from 'lodash'

// import store from 'src/store/index'
// 存储解析的token信息
export function saveCommonInfo ({ commit }, info, authorities) {
  commit('SET_USERINFO', info)
  commit('SET_AUTHORITIES', authorities)
}

// 获取厂区
export function getPlant ({ commit }) {
  commit('SET_PLANTLOADING', true)
}

// 获取车间
export function getWorkshop ({ commit }) {
  commit('SET_WORKSHOPLOADING', true)
  getWorkshops().then((res) => {
    commit('SET_WORKSHOPOPT', res.data)
  }).finally(() => {
    commit('SET_WORKSHOPLOADING', false)
  })
}

// 获取公休日
export function getDateTypeAct ({ commit }) {
  getDict('work_type').then((res) => {
    commit('SET_DATYPETE', res.data)
  })
}

// 获取班组列表
export function getTeamList ({ commit }) {
  getTeams().then((res) => {
    commit('SET_TEAMLIST', res.data)
  })
}

// 获取工艺类型
export function getProcessType ({ commit }) {
  getDict('process_type').then((res) => {
    commit('SET_PROCESSTYPE', res.data)
  })
}

// 获取设备类型
export function getEquipmentType ({ commit }) {
  commit('SET_EQUIPMENTTYPELOADING', true)
  getDict('machine_type').then((res) => {
    commit('SET_EQUIPMENTTYPEOPT', res.data)
  }).finally(() => {
    commit('SET_EQUIPMENTTYPELOADING', false)
  })
}

// 获取客制化设置的值
export function saveCustomerSet ({ commit }) {
  getCustomerSet().then(res => {
    commit('SET_SMALLSTOP', res.smallStop)
    commit('SET_STOPRANGE', { min: res.takePlaceStopMin, max: res.takePlaceStopMax })
    commit('SET_PROGRESSSET', res.sendPrecision)
    commit('SET_QUALIFYVAL', res.passRate)
    commit('SET_NORMREVISE', res.normRevise)
    commit('SET_CHECK_TIME', Math.floor(parseInt(res.repairCheck)))

    commit('SET_CUTTERLIFT', { min: res.cutterAlarmWeb, max: res.cutterWarningWeb })
    commit('SET_MOLDLIFT', { min: res.moldAlarmWeb, max: res.moldWarningWeb })
    commit('SET_PRODUCTION', { min: res.productionAlarm, max: res.productionWarning })
    commit('SET_DEFECTRATE', res.productBadWarning)
    commit('SET_SCHEMEORDERBY', res.schemeOrderBy)
    commit('SET_SYSTEMLOGO', _.isNil(res.systemLogo) ? '' : res.systemLogo)
    commit('SET_STATUSLIST', [{ key: 'machining', color: '#18D77F', value: 1, tip: '网关与设备通讯正常，并且设备正在运行', label: res.runningName },
      { key: 'halting', color: '#FF8559', value: 0, tip: '网关与设备通讯正常，但设备没有运行', label: res.stopName },
      { key: 'disconnecting', color: '#999999', value: 3, tip: '网关与设备无连接，但与服务器通讯正常', label: res.disconnectName },
      { key: 'offline', color: '#666666', value: 2, tip: '网关与云端服务器长时间无通讯', label: res.offlineName },
      { key: 'warning', color: '#E43434', value: 4, tip: '网关与设备通讯正常，且设备产生了报警信号', label: res.alarmName }])
  }).catch(() => {
    commit('SET_SMALLSTOP', 5)
    commit('SET_STOPRANGE', { min: 50, max: 200 })
    commit('SET_PROGRESSSET', 1)
    commit('SET_QUALIFYVAL', 60)
    commit('SET_NORMREVISE', 5)
    commit('SET_CHECK_TIME', 7200)

    commit('SET_CUTTERLIFT', { min: 10, max: 30 })
    commit('SET_MOLDLIFT', { min: 10, max: 30 })
    commit('SET_PRODUCTION', { min: 10, max: 50 })
    commit('SET_DEFECTRATE', 10)
    commit('SET_SCHEMEORDERBY', 0)
    commit('SET_SCHEMEORDERBY', '')
    commit('SET_STATUSLIST', [{ key: 'machining', color: '#18D77F', value: 1, tip: '网关与设备通讯正常，并且设备正在运行', label: '运行' },
      { key: 'halting', color: '#FF8559', value: 0, tip: '网关与设备通讯正常，但设备没有运行', label: '停机' },
      { key: 'disconnecting', color: '#999999', value: 3, tip: '网关与设备无连接，但与服务器通讯正常', label: '断开' },
      { key: 'offline', color: '#666666', value: 2, tip: '网关与云端服务器长时间无通讯', label: '离线' },
      { key: 'warning', color: '#E43434', value: 4, tip: '网关与设备通讯正常，且设备产生了报警信号', label: '报警' }])
  })
}

let lock = false
const subscriptions = {}
export function getWebScoket ({ dispatch, commit, state }) {
  const talentId = state.userInfo.tenant_id
  let connection = () => {
    let client = null
    let socket = new SockJS(CommonConfig.socketConfig.SOCKET_PATH + `?tenant_id_key=${talentId}`, undefined, { transports: 'websocket' })// 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
    // 获取STOMP子协议的客户端对象
    client = Stomp.over(socket)
    // 重写subscribe, unsubscribe方法
    const subscribe = client.subscribe
    const unsubscribe = client.unsubscribe
    client.subscribe = (destination, callback, headers) => {
      if (headers == null) {
        headers = {}
      }
      const sub = subscribe.call(client, destination, callback, headers)
      subscriptions[headers.id] = { callback, headers }
      return sub
    }
    client.unsubscribe = (id) => {
      delete subscriptions[id]
      return unsubscribe.call(client, id)
    }
    // 向服务器发起websocket连接
    client.connect({}, () => {
      commit('SET_SOCKET', client)
      // 连接成功订阅之前取消订阅的消息
      Object.values(subscriptions).forEach(item => {
        client.subscribe(item.headers.destination, item.callback, item.headers)
      })
    }, () => {
      commit('SET_SOCKET', client)
      // 1s内只触发一次dispatch,避免多次重复触发dispatch
      if (lock) return
      lock = true
      const timer = setTimeout(() => {
        lock = false
        dispatch('getWebScoket')
        clearInterval(timer)
      }, 1000)
    })
  }
  connection()
}

/**
 * 保存token到vuex
 * @param commit
 */
export function saveTokenData ({ commit }) {
  commit('SET_TOKEN', loadToken())
  commit('SET_REFRESHTOKEN', loadRefreshToken())
}

/**
 * 删除token
 * @param commit
 */
export function removeTokenData ({ commit }) {
  commit('SET_TOKEN', '')
  commit('SET_REFRESHTOKEN', '')
}

/**
 * 通过账号密码登录
 * @param commit
 * @param phone 电话号码
 * @param password 密码
 * @returns {Promise<unknown>}
 */
export function loginByPassword ({ commit }, { phone, password }) {
  return new Promise((resolve, reject) => {
    // 获取tid
    getCompnies(phone).then(company => {
      const tid = company.data[0].tid
      if (tid) {
        const params = {
          userName: phone,
          password,
          tid
        }
        // 执行登录方法
        login(params)
          .then((res) => {
            const response = res.data
            const token = response.access_token
            const refreshToken = response.refresh_token
            if (response.access_token && response.refresh_token) {
              saveToken(token)
              saveRefreshToken(refreshToken)
              commit('SET_TOKEN', token)
              commit('SET_REFRESHTOKEN', refreshToken)
              resolve()
            } else {
              reject()
            }
          })
          .catch(e => {
            console.log(e)
            reject()
          })
      } else {
        reject()
      }
    }).catch(() => {
      reject()
    })
  })
}

export function getSignFile ({ commit }) {
  return new Promise((resolve, reject) => {
    getMarkSetting().then(res => {
      const ret = res.data
      commit('SET_SIGNFILEDATA', ret)
      resolve(ret)
    }).catch(() => {
      reject()
    })
  })
}
